<template>
  <div class="form-modal">
    <a-modal
      :bodyStyle="{top:'0px'}"
      title="项目收款"
      :width="900"
      :visible="visible"
      @cancel="handleCancel"
    >
      <a-spin :spinning="spinning">
        <a-form :form="form" layout="inline">

          <a-descriptions :column="2" bordered size="small" style="margin-top: -10px">
            <a-descriptions-item label="姓名">{{ row_record.name }}</a-descriptions-item>
            <a-descriptions-item label="客户卡号">{{ row_record.cardNo }}</a-descriptions-item>
            <a-descriptions-item label="联系方式">{{ details.contactContent }}</a-descriptions-item>
            <a-descriptions-item label="累计消费">
              <a-statistic :value="details.totalPayableAmt" :precision="2"/>
            </a-descriptions-item>
          </a-descriptions>

          <a-descriptions bordered title="收银信息" size="small" style="margin: 10px 0;">
            <a-descriptions-item label="应收金额">
              <a-statistic :value="details.totalPayableAmt" :precision="2"/>
            </a-descriptions-item>
            <a-descriptions-item label="增值金抵扣">{{ details.totalItemGold }}</a-descriptions-item>
            <a-descriptions-item label="积分抵扣">{{ details.totalItemJf }}</a-descriptions-item>
            <a-descriptions-item label="成交金额">
              <a-statistic :value="details.totalChargeAmt" :precision="2"/>
            </a-descriptions-item>
            <a-descriptions-item label="预存款抵扣">{{ details.totalItemDeposit }}</a-descriptions-item>
            <a-descriptions-item label="券抵扣">{{ details.totalItemTicket }}</a-descriptions-item>
          </a-descriptions>

          <a-button type="primary" @click="newRow">添加</a-button>
          <a-popover @visibleChange="visibleChange" autoAdjustOverflow trigger="click" placement="right">
            <a-button type="primary" style="margin-left: 10px;">添加预存款</a-button>
            <template slot="title"><span>选择预存款</span></template>
            <template slot="content">
              <!--添加预存款--弹窗-->
              <add-deposit @selectSuccessDeposit="selectSuccessDeposit" ref="addDeposit" :row_record="row_record"/>
            </template>
          </a-popover>
          <a-popover @visibleChange="visibleChange" autoAdjustOverflow trigger="click" placement="right">
            <a-button type="primary" style="margin-left: 10px;">添加押金</a-button>
            <template slot="title"><span>选择押金</span></template>
            <template slot="content">
              <!--添加预存款--弹窗-->
              <add-deposit @selectSuccessDeposit="selectSuccessDeposit" ref="addDeposit" :row_record="row_record"/>
            </template>
          </a-popover>
          <a-form-item style="margin-left: 120px;">
            <a-checkbox-group
              v-decorator="['checkbox_value']"
              :options="options"
            />
          </a-form-item>


          <!--表格-->
          <a-table
            :locale="{emptyText:'点添加，选择收款方式'}"
            size="small"
            style="margin-top: 15px;margin-bottom:20px;"
            :columns="columns"
            :data-source="tableData"
            :rowKey="(record,index)=> index"
            :pagination="false"
          >
            <!--序号-->
            <template slot="index" slot-scope="text,record,index">
              <span>{{ index + 1 }}</span>
            </template>
            <!--收款方式-->
            <template slot="rpMode" slot-scope="text,record,index">
              <a-form-item>
                <span v-if="text===deposit_rpMode">预存款抵扣 </span>
                <template v-else>
                  <a-select
                    @change="e=>changeSelect(e, 'rpMode',index)"
                    allow-clear
                    style="width: 150px;"
                    placeholder="请选择方式"
                    v-decorator="[`rpMode${index}`, {initialValue:record.rpMode,rules: [{ required: true, message: '请选择收款方式！' }]}]">
                    <a-select-option v-for="(item,index) in rpModeArr" :key="index" :value="item.id">{{
                        item.name
                      }}
                    </a-select-option>
                  </a-select>
                </template>

              </a-form-item>
            </template>
            <!--收款金额-->
            <template slot="rpAmt" slot-scope="text,record,index">
              <a-form-item>
                <a-input
                  placeholder="请填写金额"
                  type="number"
                  @change="e => handleChange(e.target.value, record, 'rpAmt',index)"
                  v-decorator="[`rpAmt${index}`, {initialValue:text,whitespace:true,rules: [{ required: true, message: '必填！' },{validator: (r,v,c)=> validatorPrice(r,v,c,record,index)}]}]"/>
              </a-form-item>
            </template>
            <!--收款描述-->
            <template slot="rpDescribe" slot-scope="text,record,index">
              <span v-if="record.rpMode===deposit_rpMode">预存款单号：{{ text }}</span>
              <a-input
                v-else
                :value="text"
                @change="e => handleChange(e.target.value, record, 'rpDescribe',index)"
                placeholder="请填写"
              />
            </template>
            <!--操作-->
            <template slot="action" slot-scope="text,record,index">
              <a-button style="padding:0;" type="link" @click="remove(record,index)">删除</a-button>
            </template>
          </a-table>
        </a-form>
      </a-spin>
      <div slot="footer" class="g-flex g-x-between g-y-center">
        <div class="g-flex g-y-center">
          <div>
            <span style="font-size: 18px;">合计：</span>
            <span class="g-color" style="font-size: 24px;">{{ sumAmt }}</span></div>
          <div>
            <span style="font-size: 18px;margin-left: 20px;">剩余金额：</span>
            <span style="font-size: 24px;color: #E90303;">{{ surplus }}</span>
          </div>
        </div>
        <div>
          <a-button @click="visible=false">取消</a-button>
          <a-button type="primary" @click="submit" :loading="confirmLoading">确定</a-button>
        </div>
      </div>
    </a-modal>

  </div>

</template>

<script>
import {getPaymentInfo, payment} from '@/api/modular/main/customer/cashier'
import addDeposit from '@/views/customer/cashier/addDeposit'
import payType from '@/assets/flowable/js/payType'

export default {
  props: {
    row_record: {
      type: Object,
      default: () => {
      }
    }
  },
  components: {
    addDeposit,
  },
  data() {
    return {
      spinning: false,
      visible: false,
      confirmLoading: false,
      form: this.$form.createForm(this),
      details: {},
      checkbox_value: [],
      options: [
        {label: '赠送积分(无介绍人不赠送)', value: '1'},
        {label: '开具发票', value: '2'},
        {label: '收款后打印', value: '3'},
      ],
      columns: [
        {title: '序号', customRender: (text, record, index) => index + 1, width: 80},
        {title: '收款方式', dataIndex: 'rpMode', scopedSlots: {customRender: 'rpMode'}, width: 170},
        {title: '收款金额', dataIndex: 'rpAmt', scopedSlots: {customRender: 'rpAmt'}, width: 180},
        {title: '付款描述', dataIndex: 'rpDescribe', scopedSlots: {customRender: 'rpDescribe'}},
        // { title: '核销码', dataIndex: 'code', width: 120, ellipsis: true },
        {title: '操作', scopedSlots: {customRender: 'action'}, width: 100},
      ],
      rpModeArr: payType,
      default_rpMode: '09060201',
      // tableData:[{rpMode:'',rpAmt:'',code:'',rpDescribe:''}]
      tableData: [],
      deposit_rpMode: '09060207',
      qk_rpMode: '09060214'
    }
  },
  computed: {
    sumAmt() {
      let sum = 0
      this.tableData.forEach(item => {
        sum += parseFloat(item.rpAmt ? item.rpAmt : 0)
      })
      return sum
    },
    surplus() {
      const surplus = parseFloat(this.details.totalChargeAmt) - parseFloat(this.sumAmt)
      return surplus
    }
  },
  methods: {
    show() {
      this.visible = true
      this.spinning = true
      this.form.resetFields()
      this.tableData = []
      this.$nextTick(() => {
        const orderId = this.row_record.orderId
        getPaymentInfo({orderId}).then(res => {
          this.spinning = false
          if (res.code == 200) {
            console.log('111111',res.data)
            this.details = res.data
            this.tableData = this.details.billDetails
          } else {
            this.$message.warning(res.message)
          }
        })
      })
    },
    /**
     * 控制显示预存款气泡卡片
     * */
    visibleChange(visible) {
      if (visible) {
        this.$nextTick(() => {
          this.$refs.addDeposit.show()
        })
      }
    },

    /**
     * 预存款选择成功
     * */
    selectSuccessDeposit(data) {
      data.forEach(item => {
        this.tableData.push({
          originRpAmt: item.rpAmt,
          rpAmt: item.offsetAmtNo,
          rpDescribe: `${item.id}`,
          rpMode: this.deposit_rpMode,
          code: '',
        })
      })
      console.log('选择成功预存款', this.tableData)
    },
    handleCancel() {
      this.form.resetFields()
      this.visible = false
    },
    remove(record, index) {
      let temp = []
      this.tableData.forEach((item, i) => {
        if (index !== i) {
          temp.push(item)
        }
      })
      console.log(temp)
      this.tableData = temp
      // this.tableData.splice(index,1)
    },
    newRow() {
      const len = this.tableData.length
      if (len > 0 && this.tableData[len - 1].isNew) {
        this.$message.warning('新增记录已存在！')
        return
      }
      this.tableData.push({
        rpDescribe: '',
        rpAmt: '',
        rpMode: '',
        code: ''
      })
    },
    /**
     改变付款方式
     * */
    changeSelect(value, column, index) {
      console.log('改变付款方式', value)
      this.tableData[index][column] = value
    },
    /**
     表单校验
     * */
    validatorPrice(rule, value, callback, record, index) {
      if (value.length > 1 && value.substring(0, 1) == '0') {
        callback('不能以0开头')
      }
      if (value < 0) {
        callback('必须为非负数')
      }

      if (parseFloat(value) > parseFloat(this.details.totalChargeAmt)) {
        callback('不能大于成交金额')
      }
      //是预存款抵扣
      if (record.rpMode === this.deposit_rpMode) {
        if (parseFloat(value) > parseFloat(record.originRpAmt)) {
          callback('超出预存金额')
        }
      }
      callback()
    },

    handleChange(value, record, column, index) {
      this.tableData[index][column] = value
    },
    /**
     提交表单
     * */
    submit() {
      const {form: {validateFields}} = this
      this.confirmLoading = true
      validateFields((errors, values) => {
        if (errors) {
          this.confirmLoading = false
          return
        }
        if (this.surplus > 0) {
          // this.confirmLoading = false
          // this.$message.error('剩余金额未收完')
          // return
          this.tableData.push({
            rpMode: this.qk_rpMode,
            rpAmt: this.surplus
          })
        }
        let isInvoice = ''
        if (values.checkbox_value) {
          isInvoice = values.checkbox_value.includes('2') ? true : false
        }
        const params = {
          orderId: this.row_record.orderId,
          billDetails: this.tableData,
          customerId: this.row_record.customerId,
          payAmt: this.sumAmt,
          isInvoice
        }
        payment(params).then(res => {
          if (res.code == 200) {
            this.$message.success({
              content: '提交成功',
              duration: 1,
              onClose: () => {
                this.visible = false
                this.$emit('itemChargeSuccess')
              }
            })
          } else {
            this.$message.warning(res.message)
          }
          this.confirmLoading = false
        }).finally(() => {
          this.confirmLoading = false
        })
      })
    },
  }
}
</script>

<style lang="less" scoped>
/deep/ .ant-modal {
  top: 50px;
}

.col-form-item {
  padding: 0 4px 20px;
}

/deep/ .ant-modal-footer {
  border-top: none !important;
}

/deep/ .ant-form-inline .ant-form-item-with-help {
  margin-bottom: 0;
}
</style>

